﻿var ctx;  
var dir = 'left';
this.actualColor = WHITE;
this.hit;
this.intervalHandler = "";
const RED = "rgb(255,0,0)";
const WHITE = "rgb(255,255,255)";
const GREEN = "rgb(0,255,0)";
const YELLOW = "rgb(255,255,0)";

function initialize() {
	var location = document.getElementById('location').value;
	var canvas = document.getElementById('canvas');
	if (canvas.getContext) {
		ctx = canvas.getContext('2d');
	} else {
		alert("We're sorry, but your browser does not support the canvas tag. Please use any web browser other than Internet Explorer.");
	}
	// The start position of paddle for each player
	this.p1 = {
		'x' : 35,
		'y' : 70
	};
	this.p2 = {
		'x' : canvas.width - 45,
		'y' : 70
	};
	this.p3 = {
		'x' : 85,
		'y' : 70
	};
	this.p4 = {
		'x' : canvas.width - 95,
		'y' : 70
	};
	
	// my position
	this.playerPos = {
		'x' : 0, // x pos
		'y' : 0, // y pos
		'prevX':0, // previous x position
		'prevY':0 // previous y position
	};
	this.xArray = [p1['x'], p2['x'], p3['x'], p4['x']];
	// Ball Position
	this.ballPosition = {
		'x' : 400,
		'y' : 210,
	};
	// Previous Ball position needed to clear ball
	previousBallPosition = {
		'x' : 400,
		'y' : 210
	};

	// Size of paddle
	paddleLength = 7;
	gridSize = 10;
	// paddle size in pixels
	height = gridSize * paddleLength;
	// one step in px
	ballStep = 5;

	ctx.fillStyle = actualColor;

}
function start() { 
	/*
	 * This function start interval to compute actuall ball position. Only for
	 * Host-Client.
	 */
	 intervalHandler = setInterval(executeBallMove, 33); 
}

function drawPaddle() 
{	
	/*
	 * This function draw paddle for player
	 */
	ctx.fillStyle = actualColor;
	ctx.clearRect(playerPos['prevX'], playerPos['prevY'], gridSize, height);
	ctx.fillRect(playerPos['x'], playerPos['y'], gridSize, height);
}
function drawOpponentPaddle(playerNr){
	/*
	 * This function draw opponent paddles, 'playerNr' says which paddle redraw.
	 */
	switch (playerNr) {
	case 1:
		ctx.fillStyle = WHITE;
		ctx.clearRect(p1['prevX'], p1['prevY'], gridSize, height);
		ctx.fillRect(p1['x'], p1['y'], gridSize, height);
		break;
	case 2:
		ctx.fillStyle = RED;
		ctx.clearRect(p2['prevX'], p2['prevY'], gridSize, height);
		ctx.fillRect(p2['x'], p2['y'], gridSize, height);
		break;
	case 3:
		ctx.fillStyle = YELLOW;
		ctx.clearRect(p3['prevX'], p3['prevY'], gridSize, height);
		ctx.fillRect(p3['x'], p3['y'], gridSize, height);
		break;
	case 4:
		ctx.fillStyle = GREEN;
		ctx.clearRect(p4['prevX'], p4['prevY'], gridSize, height);
		ctx.fillRect(p4['x'], p4['y'], gridSize, height);
		
	break;
	default:
		break;
	}
}

function changePlayerPos(x, y, playerNr){
	/*
	 * This function set player new position, after recieved message which new
	 * positin x - new X position y - new Y position playerNr - which player
	 * moved
	 */
	switch (playerNr) {
	case 1:
		p1['prevY'] = p1['y'];
		p1['prevX'] = p1['x'];
		p1['y'] = y;
		break;
	case 2:
		p2['prevY'] = p2['y'];
		p2['prevX'] = p2['x'];
		p2['y'] = y;
		break;
	case 3:
		p3['prevY'] = p3['y'];
		p3['prevX'] = p3['x'];
		p3['y'] = y;
		break;
	case 4:
		p4['prevY'] = p4['y'];
		p4['prevX'] = p4['x'];
		p4['y'] = y;
		break;
	default:
		break;
	}
}
function setPlayerPos(playerNr) {
	/*
	 * After joining to game, server send a message with connected players, this
	 * function give you your position according to which player you are
	 */
	switch (playerNr) {
	case 1:
		playerPos['x'] = p1['x'];
		playerPos['y'] = p1['y'];
		playerPos['prevX'] = p1['x'];
		actualColor = WHITE;
		drawPaddle();
		break;
	case 2:
		playerPos['x'] = p2['x'];
		playerPos['y'] = p2['y'];
		playerPos['prevX'] = p2['x'];
		actualColor = RED;
		drawPaddle();
		break;
	case 3:
		playerPos['x'] = p3['x'];
		playerPos['y'] = p3['y'];
		playerPos['prevX'] = p3['x'];
		actualColor = YELLOW;
		drawPaddle();
		break;
	case 4:
		playerPos['x'] = p4['x'];
		playerPos['y'] = p4['y'];
		playerPos['prevX'] = p4['x'];
		actualColor = GREEN;
		drawPaddle();
		break;
	default:
		break;
	}
}

function drawBall() {
	ctx.fillStyle = WHITE;
	ctx.clearRect(previousBallPosition['x'], previousBallPosition['y'],
			gridSize, gridSize);
	ctx.fillRect(ballPosition['x'], ballPosition['y'], gridSize, gridSize);
	
	// refresh is needed if ball 'clear' paddle.
	refresh(players.length);
}
function refresh(nr) {
	var i = players.length;
	while (i >= 1) {
		drawOpponentPaddle(i)
		i--;
	}
}
document.onkeydown = function(event) {
	var keyCode;

	if (event == null) {
		keyCode = window.event.keyCode;
	} else {
		keyCode = event.keyCode;
	}

	if (isStarted) {
		switch (keyCode) {

		// up
		case 38:
			moveUp();		// execute move
			positionUp(); // Send message to server with new position
			break;

		// down
		case 40:
			moveDown();
			positionDown(); // Send message to server with new position
			break;

		default:
			break;
		}
	}
}
function upPosition() {
	playerPos['prevY'] = playerPos['y'];
	return playerPos['y'] - gridSize;
}

function downPosition() {
	playerPos['prevY'] = playerPos['y'];
	return playerPos['y'] + height;
}
function moveUp() {
	if (upPosition() >= 0) {
		executeMove(playerPos['x'], upPosition());
	}
}

function moveDown() {
	if (downPosition() < canvas.height) {
		executeMove(playerPos['x'], playerPos['y'] + gridSize);

	}
}

function executeMove(xValue, yValue) {
	playerPos['y'] = yValue;
	playerPos['x'] = xValue;
	}
	
function executeBallMove() {
	changeMoveDirection();
	moveBall();
		
}
function changeMoveDirection() {
	/*
	 * This function is responsible to change ball direction if ball hit: edge
	 * of canvas or paddle
	 */
	
	hit = xArray.indexOf(ballPosition['x']); 
	if (hit != -1 && hit < players.length) // Ball is on X position of player
		if (computePaddle(hit)) { // if ball is on Y position of player
			var hitPlace = paddleBody.length;
			if (hitPlace <= 6) // hit on the top of paddle
				if (hit == 0 || hit == 2) // 0 or 2 is a number of player on
											// the left side
					dir = 'rightUp';
				else
					dir = 'leftUp';
			else if (hitPlace == (7 || 8)) // hit on the middle of paddle
				if (hit == 0 || hit == 2)
					dir = 'right';
				else
					dir = 'left';
			else if (hitPlace <= 14) // hit on the bottom of paddle
				if (hit == 0 || hit == 2)
					dir = 'rightDown';
				else
					dir = 'leftDown';
		}
	// hit top edge of canvas
	if (ballPosition['y'] == 0) {
		if (dir == 'rightUp')
			dir = 'rightDown';
		if (dir == 'leftUp')
			dir = 'leftDown';
	}
	// hit bottom edge of canvas
	if (ballPosition['y'] == canvas.height) {
		if (dir == 'rightDown')
			dir = 'rightUp';
		if (dir == 'leftDown')
			dir = 'leftUp';
	}
	// Ball is out of board
	if (ballPosition['x'] == 0) {
		ctx.clearRect(ballPosition['x'], ballPosition['y'],
				gridSize, gridSize);
		sendScore(1);
	}
	if (ballPosition['x'] == canvas.width) {
		ctx.clearRect(previousBallPosition['x'], previousBallPosition['y'],
				gridSize, gridSize);
		sendScore(0);
		
	}
}
function computePaddle(playerNr) {
	/*
	 * This function compute body of paddle. For example start position of
	 * rectangle (paddle) is 0,0 width = 10 and height = 70. If ball is on
	 * position 0,50 it hits paddle. Without this function ball would go straight through the paddle
	 */
	var pos = playerNr;
	switch (playerNr) {
	case 0:
		pos = p1['y'];
		break;
	case 1:
		pos = p2['y'];
		break;
	case 2:
		pos = p3['y'];
		break;
	case 3:
		pos = p4['y'];
		break;
	default:
		break;
	}
	var i = 0;
	paddleBody = new Array();
	for ( var int = 0; int < height;) {

		paddleBody[i] = parseInt(pos) + int;
		int += ballStep;
		if (paddleBody[i] == ballPosition['y']) {
			return true;
		}
		i++;
	}
	return false;
}
function moveBall() {
	/*
	 * This function execute ball move according to actual direction
	 */
	switch (dir) {
	case 'left':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] = ballPosition['x'] - ballStep;
		sendBallPosToServer();
		drawBall();
		break;

	case 'right':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] += ballStep;
		sendBallPosToServer();
		drawBall();
		break;
	case 'leftUp':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] -= ballStep;
		ballPosition['y'] -= ballStep;
		sendBallPosToServer();
		drawBall();
		break;

	case 'rightUp':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] += ballStep;
		ballPosition['y'] -= ballStep;
		sendBallPosToServer();
		drawBall();
		break;
	case 'leftDown':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] -= ballStep;
		ballPosition['y'] += ballStep;
		sendBallPosToServer();
		drawBall();
		break;

	case 'rightDown':
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] += ballStep;
		ballPosition['y'] += ballStep;
		sendBallPosToServer();
		drawBall();
		break;
	}
	
}
